package com.chang.dp.controller;

import com.alibaba.fastjson.JSON;
import com.chang.dp.utils.EpubUtil;
import lombok.extern.slf4j.Slf4j;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Metadata;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.epub.EpubReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

@RestController
@RequestMapping("/api/epub")
@Slf4j
public class EpubController {
    @Value("${system.upload-path}")
    String uploadPath;

    String epubFilePath = "F:\\阿里云盘下载\\电子书\\【01】\\00\\半小时漫画中国史3.epub";
    @GetMapping("/read")
    public void read() {
        try {
            EpubReader epubReader = new EpubReader();
            Book book = epubReader.readEpub(Files.newInputStream(new File(epubFilePath).toPath()));
            Metadata metadata = book.getMetadata();
            String json = JSON.toJSONString(metadata);
            log.info("图书信息: {}", json);
            List<Resource> resources = book.getContents();
            Resource resource = resources.get(3);
            Resource imageReSource = book.getResources().getByHref("Image00002.jpg");
            InputStream imageInputStream = imageReSource.getInputStream();
            // 保存到uploadPath
            EpubUtil.saveImage(imageInputStream, uploadPath, "Image00002.jpg");

//            String content = new String(resource.getData(), StandardCharsets.UTF_8);
//            log.info("content: {}", content);
//            for (Resource resource : resources) {
//                String content = new String(resource.getData(), StandardCharsets.UTF_8);
//                String title = EpubUtil.getTitle(EpubUtil.getDocument(content));
//                log.info("title: {}", title);
//            }
        } catch (IOException e) {
            log.error("读取失败 ---> " + e.getMessage());
        }
    }
}
